<template>
  <div>
    <div ref="chart" style="width:100%;height:380px"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import chinaMap from '../chart/china.json';
import axios from 'axios';

export default {
  data() {
    return {
      chart: null,
      mapType: 'china',
      dataTable: []
    };
  },
  mounted() {
    this.initChart();
    this.getData();
  },
  watch: {
    dataTable: 'updateChart'
  },
  methods: {
    async getData() {
      try {
        const res = await axios.get('http://localhost:8080/data/user/province');
        this.dataTable = res.data.data;
      } catch (err) {
        console.error('Failed to fetch data:', err);
      }
    },
    initChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart);
        echarts.registerMap('china', chinaMap);
      }
      this.updateChart();
    },
    updateChart() {
      const option = this.getChartOption();
      this.chart.setOption(option);
    },
    getChartOption() {
      return {
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>{c} 件'
        },
        visualMap: {
          min: 0,
          max: 200,
          left: 'left',
          top: 'bottom',
          text: ['高', '低'],
          calculable: true
        },
        series: [
          {
            type: 'map',
            mapType: this.mapType,
            roam: true,
            label: {
              show: true
            },
            data: this.dataTable
          }
        ]
      };
    },
    changeMap() {
      this.mapType = 'world';
      this.updateChart();
    }
  }
};
</script>

<style>
</style>
